package io.gitee.kotle.base.library

import androidx.lifecycle.MutableLiveData
import io.gitee.kotle.android.mvvm.MvvmViewModel
import io.gitee.kotle.android.utils.StatusData
import io.gitee.kotle.android.utils.isRunning
import io.gitee.kotle.android.utils.toast
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Job
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext

/**
 *
 * 描述：
 *
 * 创建人：jiale.wei
 * 创建时间：2022/1/17 3:54 下午
 *
 */
open class BaseViewModel : MvvmViewModel() {
    /**
     * 启动一个协程作用域
     */
    inline fun <T> MutableLiveData<StatusData<T>>.launch(
        toastError: Boolean = true,
        checkIsRunning: Boolean = true,
        context: CoroutineContext = EmptyCoroutineContext,
        start: CoroutineStart = CoroutineStart.DEFAULT,
        crossinline errorBlock: ((Throwable) -> T?) = {
            if (toastError) {
                it.message?.toast()
            }
            null
        },
        crossinline finallyBlock: (() -> Unit) = {},
        crossinline block: suspend CoroutineScope.() -> T
    ): Job? {
        if (checkIsRunning && this.isRunning) {
            return null
        }
        return runOnScope(toastError, context, start, errorBlock, finallyBlock, block)
    }
}